from pydoc import classname
from unicodedata import name
from django.core.management.base import BaseCommand, CommandError
from course.models import CourseInfo
from course.utils import CourseTimeUtil as CTU
import json

# 加载本地json课程信息文件
class Command(BaseCommand):
    help = "Load the course infomation file into database"

    def add_arguments(self, parser):
        parser.add_argument("filename", type=str, help="need .json")

    def handle(self, *args, **options):
        print(options["filename"])
        filename = options["filename"]
        course_data = json.load(open(filename, encoding="utf-8"))

        exist_course_dict = {}
        progress_count = 0
        progress_pct = 1
        for ci in course_data:
            # 重复课程检测 : 课程标识名、开课老师、年级相同
            if CourseInfo.objects.filter(
                classname=ci["classname"], name=ci["name"], nj=ci["nj"]
            ).exists():
                if ci["classname"] in exist_course_dict:
                    exist_course_dict[ci["classname"]] += 1
                else:
                    exist_course_dict[ci["classname"]] = 1
            else:
                CourseInfo.objects.create(
                    title=ci["title"],
                    zcStr=ci["zcStr"],
                    bh=ci["bh"],
                    place=ci["place"],
                    classname=ci["classname"],
                    time=CTU.encode(ci["time"]),
                    kkyx=ci["kkyx"],
                    name=ci["name"],
                    nj=ci["nj"],
                    skyx=ci["skyx"],
                )

            # 进度报告
            progress_count += 1
            if progress_count > len(course_data) * progress_pct / 10:
                print("导入数据进度 %d%%" % (progress_pct * 10))
                progress_pct += 1
        print("导入数据进度 %d%%" % (100))

        # 重复课程检测报告
        print("重复课程共%d条" % len(exist_course_dict))
        for title, count in exist_course_dict.items():
            print("课程名:{0}  重复次数:{1}".format(title, count))

        print(
            "课程数据导入完成, 成功导入%d条课程信息"
            % (len(course_data) - sum(exist_course_dict.values()))
        )
